<?php

// +----------------------------------------------------------------------
// | Easyadmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\user;

use app\admin\model\website\BalanceRecord;
use app\admin\model\website\Users;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\facade\Db;
use think\App;
use broadcast\redis\setRedis;

use broadcast\redis\RedisRecord;

/**
 * Class Admin
 * @package app\admin\controller\user
 * @ControllerAnnotation(title="站点管理")
 */
class UserBalance extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new BalanceRecord();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            
            foreach ($where as &$item) {
                if ($item[0] == 'roomid') {
                    $item[0]= 'u.rooms';
                }else {
                    $item[0]= 'b.'.$item[0];
                }
            }
            
            $countModel = $this->model->alias('b')->join("users u",'u.id=b.uid');
            if (session("admin.group") != 1 && session("admin.group") != 5) {
                $countModel = $countModel->where("b.uid",session('admin.id'));
            }else if (session("admin.group") == 5) {
                $countModel = $countModel->where("b.rooms","in",session("admin.rooms"));
            }
            $count = $countModel->where($where)
                ->count();
            $listModel = $this->model->alias('b')->join("users u",'u.id=b.uid');;
            if (session("admin.group") != 1 && session("admin.group") != 5) {
                $listModel = $listModel->where("b.uid",session('admin.id'));
            }else if (session("admin.group") == 5) {
                $listModel = $listModel->where("b.rooms","in",session("admin.rooms"));
            }
            $list  = $listModel->where($where)->page($page, $limit)
                ->order($this->sort)
                ->field("b.*,u.rooms as roomid")
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }

        $balance = Users::where("id",session("admin.id"))->value("balance");
        $this->assign("balance",$balance);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function recharge()
    {


        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $data = [
                'price' => $post['price'],
                'type'  => 1,
                'create_time' => time(),
                'mark'  => '后台充值',
                'mold'  => '1',
                'uid'   => session("admin.id")
            ];
            try {
                $save = $this->model->save($data);

                
                Users::where("id",session("admin.id"))->inc("balance",(float)$data['price'])->save();
                
                $userinfo = Users::where("id",session("admin.id"))->find()->toArray();
                setRedis::setCache(session("website"),"usersList#".$userinfo['id'].":".$userinfo['username'],$userinfo,0);
                

            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        if ($save){
            $redEnvelopesHandle = new RedisRecord(session("website"),'redEnvelopesHandle');
            $redEnvelopesHandle->delEnvelopes($id);
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        } 
    }

}
